<template>
  <a-layout class="fm-container">
    <!--设计器顶部start-->
    <a-layout-header class="fm-header-bar" style="height: 50px">
      <a-row>
        <a-col :span="6">
          <h3>【{{$attrs['port-let'].portletName}}】{{$t('m.common.button.setting')}}</h3>
        </a-col>
        <a-col :span="18">
          <div class="btn-group">
            <a-button type="primary" :style="btnStyle" @click="savePortalDesign"> {{$t('m.common.button.save')}} </a-button>
            <a-button v-if="resourceType" :style="btnStyle" @click="handleCommand">
              {{ $t('m.portalDesign.actions.deletPort') }}
            </a-button>
            <a-button v-if="clearable" :style="btnStyle" @click="handleClear">
              {{ $t('m.common.button.clear') }}
            </a-button>
            <a-button v-if="preview" :style="btnStyle" @click="handlePreview">
              {{ $t('m.common.button.preview') }}
            </a-button>
            <a-button :style="btnStyle" @click="closeModal"> {{$t('m.common.button.cancel')}} </a-button>
          </div>
        </a-col>
      </a-row>
    </a-layout-header>
    <!--设计器内容区-->
    <a-layout class="fm-container-center">
      <!--门户小页右边栏-->
      <a-layout-sider width="200px" v-model="leftCollapsed" :collapsed-width="0">
        <div
          class="drawer-left"
          :class="{ leftactive: isleftActive, leftclose: isleftClose }"
          @click="clickBtn('left')"
        >
          <ych-icon :type="isleftClose ? 'right' : 'left'" />
        </div>
        <div class="fm-container-center-left">
          <!-- 基础组件 -->
          <template v-if="basicFields.length">
            <div class="fm-left-title">{{ $t('m.portalDesign.components.portletPage.title') }}</div>
            <draggable
              tag="ul"
              :list="basicComponents"
              v-bind="{
                group: { name: 'people', pull: 'clone', put: false },
                sort: false,
                ghostClass: 'ghost'
              }"
              @end="handleMoveEnd"
              @start="handleMoveStart"
              :move="handleMove"
            >
              <template v-for="(item, index) in basicComponents">
                <li
                  v-if="basicFields.indexOf(item.type) >= 0"
                  class="fm-left-li-list"
                  :class="{ 'no-put': item.type == 'divider' }"
                  :key="index"
                >
                  <a>
                    <span>{{ item.name }}</span> <ych-icon class="drag-icon" type="drag" />
                  </a>
                </li>
              </template>
            </draggable>
          </template>
          <template v-if="layoutFields.length">
            <div class="fm-left-title">{{ $t('m.portalDesign.components.portletPage.layoutTemp') }}</div>
            <ul>
              <template v-for="(item, index) in gridlayoutComponents">
                <li
                  v-if="layoutFields.indexOf(item.type) >= 0"
                  class="fm-left-li-list no-put fm-left-li-modeltemp"
                  :key="index"
                  @click="handleAddTemp(item)"
                >
                  <a>
                    <span>{{ item.name }}</span>
                  </a>
                </li>
              </template>
            </ul>
          </template>
        </div>
      </a-layout-sider>
      <!--设计区-->
      <a-layout-content :class="{ 'widget-empty': widgetForm.list.length == 0 }">
        <widget-form
          v-if="!resetJson"
          ref="widgetForm"
          :data="widgetForm"
          :select.sync="widgetFormSelect"
          @handleWidgetOpensSet="clickBtn('right')"
        />
      </a-layout-content>
      <!--属性设置区-->
      <a-layout-sider
        width="200px"
        class="fm-widget-config-container drawer-box-right"
        :class="{ draweractive: isActive, drawerclose: isClose }"
        v-model="rightCollapsed"
        :collapsed-width="0"
        :default-collapsed="true"
      >
        <a-layout>
          <div
            class="drawer-handle"
            :class="{ rightactive: isActive, rightclose: isClose }"
            @click="clickBtn('right')"
          >
            <ych-icon class="" :type="isClose ? 'left' : 'right'" />
          </div>
          <a-layout-header class="fm-header-bar" style="height: 45px">
            <div
              class="fm-config-tab"
              :class="{ active: configTab == 'widget' }"
              @click="handleConfigSelect('widget')"
            >
              {{ $t('m.portalDesign.config.widget.title') }}
            </div>
          </a-layout-header>
          <a-layout-content class="fm-config-content">
            <widget-config v-show="configTab == 'widget'" :data.sync="widgetFormSelect" />
          </a-layout-content>
        </a-layout>
      </a-layout-sider>
    </a-layout>
    <!--预览弹窗-->
    <cus-dialog
      :visible="previewVisible"
      :title="$t('m.common.button.preview')"
      :action="false"
      @on-close="previewVisible = false"
      ref="widgetPreview"
    >
      <generate-form
        @on-change="handleDataChange"
        v-if="previewVisible"
        :data="widgetForm"
        ref="generateForm"
      />
    </cus-dialog>
  </a-layout>
</template>

<script>
import Draggable from 'vuedraggable';
import WidgetConfig from './WidgetConfig';
import WidgetForm from './WidgetForm';
import CusDialog from './CusDialog';
import GenerateForm from './GenerateForm';
import { gridlayoutComponents } from './js/componentsConfig.js';
import { portLetApiMixin } from '../../mixins/portLetApiMixin.js';
export default {
  name: 'FmMakingForm',
  components: {
    Draggable,
    WidgetConfig,
    WidgetForm,
    CusDialog,
    GenerateForm
  },
  props: {
    preview: {
      type: Boolean,
      default: false
    },
    generateCode: {
      type: Boolean,
      default: false
    },
    generateJson: {
      type: Boolean,
      default: false
    },
    upload: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    basicFields: {
      type: Array,
      default: () => [
        'input',
        'textarea',
        'number',
        'radio',
        'checkbox',
        'time',
        'date',
        'rate',
        'color',
        'select',
        'switch',
        'slider',
        'text',
        'text2',
        'bpmtask',
        'smallPage'
      ]
    },
    advanceFields: {
      type: Array,
      default: () => ['blank', 'imgupload', 'editor', 'cascader']
    },
    layoutFields: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      basicComponents: [],
      gridlayoutComponents,
      resetJson: false,
      widgetForm: {
        list: [],
        config: {
          gutter: '15px',
          labelWidth: 100,
          labelPosition: 'right',
          size: 'small'
        }
      },
      configTab: 'widget',
      widgetFormSelect: null,
      previewVisible: false,
      codeVisible: false,
      uploadVisible: false,
      drawerVisible: true,
      blank: '',
      htmlTemplate: '',
      vueTemplate: '',
      uploadEditor: null,
      jsonEg: `{
         "list": [],
         "config": {
         "labelWidth": 100,
         "labelPosition": "top",
         "size": "small"
         }
      }`,
      codeActiveName: 'vue',
      isActive: false,
      isClose: false,
      isleftActive: false,
      isleftClose: false,
      leftCollapsed: false,
      rightCollapsed: true,
      btnStyle: { marginLeft: '10px' }
    };
  },
  mixins: [portLetApiMixin],
  mounted() {
    this._loadComponents();
    //console.log('this.$attrs', this.$attrs)
  },
  computed: {
    resourceType() {
      if (this.$attrs['port-let'] && this.$attrs['port-let'].resourceType == '2') {
        return true;
      } else {
        return false;
      }
    },
    isDefault() {
      if (this.$attrs['port-let'] && this.$attrs['port-let'].isDefault == '0') {
        return true;
      } else {
        return false;
      }
    }
  },
  methods: {
    _loadComponents() {
      this.getBasicComponents(res => {
        this.basicComponents = res.map((item, index) => {
          return {
            type: 'smallPage', // 组件类型，保持唯一
            name: item.menuName,
            url: item.menuUrl,
            icon: 'icon-input', //组件展示icon, 如果需要自定义，请参考 如何自定义图标
            options: {
              // 组件配置信息，根据自定义组件自己添加配置
              title: item.menuName, //标题
              titleRequired: item.showTitle === '1' ? true : false, //显示标题
              moreUrl: item.moreUrl, //跳转路由组件地址
              menuPath: item.menuPath, //路由路径
              menuRouteName: item.menuRouteName, //路由名称
              refresh: item.refresh //刷线频率
            },
            x: 0,
            y: 0,
            w: 12,
            h: item.height != null ? item.height / 10 : 20,
            i: index + '',
            id: item.id
          };
        });
      });
      this.gridlayoutComponents = this.gridlayoutComponents.map(item => {
        return {
          ...item,
          name: this.$t(`m.portalDesign.components.portletPage.grid.${item.name}`)
        };
      });
    },
    handleConfigSelect(value) {
      this.configTab = value;
    },
    handleMoveEnd(evt) {
      //console.log('end', evt);
    },
    handleMoveStart({ oldIndex }) {
      //console.log('start', oldIndex, this.basicComponents);
    },
    handleMove() {
      return true;
    },
    handlePreview() {
      //console.log(this.widgetForm);
      this.previewVisible = true;
    },
    handleClose() {
      this.previewVisible = false;
    },
    handleClear() {
      let obj = {
        list: [],
        config: {
          ...this.widgetForm.config
        }
      };
      this.widgetForm = obj;
      this.widgetFormSelect = {};
    },
    setJSON(json) {
      this.widgetForm = json;

      if (json.list.length > 0) {
        this.widgetFormSelect = json.list[0];
      }
    },
    handleDataChange(field, value, data) {
      //console.log(field, value, data);
    },
    handleAddTemp(item){
      let widgetData = JSON.parse(item.columns)
      this.setJSON(widgetData)
    },
    handleCommand() {
      let that = this;
      this.$confirm({
        title: this.$t('m.common.label.prompt'),
        content: this.$t('m.portalDesign.description.que-ren-shan-chu-ci-men-hu-ma'),
        closable: true,
        onOk() {
          return that.deletePortlet(that.$attrs['port-let'].id);
        },
        onCancel() {}
      });
    },
    clickBtn(type) {
      if (type == 'right') {
        if (this.isActive) {
          this.isClose = !this.isClose;
        } else {
          this.isActive = true;
        }
        this.rightCollapsed = !this.rightCollapsed;
      } else if (type == 'left') {
        this.leftCollapsed = !this.leftCollapsed;
        this.isleftActive = true;
        this.isleftClose = !this.isleftClose;
      }
    },
    closeModal() {
      this.$emit('closeModal');
    },
    savePortalDesign() {
      this.$emit('savePortalDesign');
    }
  },
  watch: {
    widgetForm: {
      deep: true,
      handler(val) {
        this.$emit('updateDesign', val);
      }
    },
    $lang() {
      this._loadComponents();
    }
  }
};
</script>

<style lang="less" scoped>
.widget-empty {
  background-position: 50%;
}
/*收缩功能 start*/
.drawer-handle {
  position: absolute;
  right: 0;
  width: 15px;
  top: 50%;
  height: 40px;
  z-index: 99999;
  padding: 10px 0;
  background: #fff;
  cursor: pointer;
  border-bottom-left-radius: 3px;
  border-top-left-radius: 3px;
  box-shadow: -4px 0 4px 0 #ddd;
  i {
    color: dodgerblue;
  }
}
.drawer-left {
  position: absolute;
  left: 200px;
  width: 15px;
  top: 50%;
  height: 40px;
  z-index: 99999;
  padding: 10px 0;
  background: #fff;
  cursor: pointer;
  border-bottom-right-radius: 3px;
  border-top-right-radius: 3px;
  i {
    color: dodgerblue;
  }
}
.drawer-box-left {
  position: static !important;
  background: #fff;
  left: 0;
  bottom: 0;
  top: 0;
  border: 0 solid #ddd;
  border-top: 0;
}
.drawer-box-right {
  position: absolute;
  background: #fff;
  right: 0;
  bottom: 0;
  top: 0;
  border: 0 solid #ddd;
  border-top: 0;
  box-shadow: -2px 0 6px 0 #ddd;
}
.draweractive {
  animation: opendoor 0.4s normal forwards;
}

@keyframes opendoor {
  from {
    width: 0;
  }
  to {
    width: 200px;
  }
}
// 关
.drawerclose {
  animation: close 0.4s normal forwards;
}

@keyframes close {
  0% {
    width: 200px;
  }
  100% {
    width: 0;
  }
}
.rightactive {
  animation: rhandleopen 0.2s normal forwards;
}
.rightclose {
  animation: rhandleclose 0.2s normal forwards;
}
.leftactive {
  animation: lhandleopen 0.2s normal forwards;
}
.leftclose {
  animation: lhandleclose 0.2s normal forwards;
}

@keyframes rhandleclose {
  0% {
    right: 200px;
  }
  100% {
    right: 0;
  }
}

@keyframes rhandleopen {
  0% {
    right: 0;
  }
  100% {
    right: 200px;
  }
}

@keyframes lhandleclose {
  0% {
    left: 200px;
  }
  100% {
    left: 0;
  }
}

@keyframes lhandleopen {
  0% {
    left: 0;
  }
  100% {
    left: 200px;
  }
}
/*收缩功能 end*/
.cusdialogbody {
  height: 97%;
  overflow: hidden;
  margin: auto;
  margin-top: 0.5% !important;
}
/* antd 样式start */
.fm-container {
  .ant-layout-sider,
  .ant-layout-header {
    background: #fff !important;
  }
  .ant-layout-header {
    padding: 0;
    line-height: 45px;
    border-bottom: 1px solid #ddd;

    .btn-group {
      text-align: right;
      padding: 0 10px;
    }
  }
  .ant-layout-content {
    overflow: auto;
  }
}
/* antd 样式end */
</style>
